package com.hcc.flow.server.service.sys;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.common.where.AuditLogWhere;
import com.hcc.flow.server.dao.sys.SysLogsDao;
import com.hcc.flow.server.model.sys.SysAuditLogs;
import com.hcc.flow.server.model.sys.SysLogs;
import com.hcc.flow.server.where.sys.LogWhere;

@Service
public class SysLogService  {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	@Autowired
	private SysLogsDao sysLogsDao;

	/**
	 * 将该方法改为异步,用户由调用者设置
	 *
	 * @param sysLogs
	 * @see com.hcc.flow.server.advice.LogAdvice
	 */
	@Async
	
	public void save(SysLogs sysLogs) {
		// LoginUser user = UserUtil.getLoginUser();
		if (sysLogs == null || sysLogs.getUserId() == null) {
			return;
		}

		// sysLogs.setUser(user);
		sysLogsDao.save(sysLogs);
	}

	@Async
	
	public void save(String userId, String module, Boolean flag, String remark) {
		SysLogs sysLogs = new SysLogs();
		sysLogs.setFlag(flag);
		sysLogs.setModule(module);
		sysLogs.setRemark(remark);
		sysLogs.setLogType(1);// 1运营系统
		sysLogs.setUserId(userId);
		/*
		 * SysUser user = new SysUser(); user.setUserId(userId); sysLogs.setUser(user);
		 */

		sysLogsDao.save(sysLogs);

	}

	
	public void deleteLogs() {

		Date date = DateUtils.addMonths(new Date(), -3);
		String time = DateFormatUtils.format(date, DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
		
		try {
			int sysLogDelCount = sysLogsDao.deleteLogs(time);
			log.debug("删除{}之前‘系统操作’日志{}条", time, sysLogDelCount);
		} catch (Exception e) {
			log.error("删除系统操作日志失败，失败原因{}",e.getMessage());
		}
	}

	
	public PageInfo<SysLogs> findAllLogs(LogWhere ewhere) {
		PageHelper.startPage(ewhere.getOffset(), ewhere.getLimit());
		if (ewhere.getSqlOrder() == null || ewhere.getSqlOrder().isEmpty()) {
			ewhere.setSqlOrder("t.create_time desc ");
		}
		PageHelper.orderBy(ewhere.getSqlOrder());
		List<SysLogs> log = sysLogsDao.LogList(ewhere);
		PageInfo<SysLogs> result = new PageInfo<SysLogs>(log);
		return result;
	}

	
	@Transactional
	public void saveAuditLogs(SysAuditLogs sysAuditLogs) {
		if (sysAuditLogs == null)
			throw new IllegalArgumentException("保存日志传入的参数为空");
		int num = sysLogsDao.saveAuditLogs(sysAuditLogs);
		if (num < 1)
			throw new IllegalArgumentException("保存日志失败");

	}

	
	public List<SysAuditLogs> findAuditLogs(AuditLogWhere auditLogWhere) {
		return sysLogsDao.LogAuditList(auditLogWhere);
	}
}
